<?php
// This controller handles the logic for the my sites page

class MySitesController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
	public function actionBuyer() 
	{
		if(Yii::app()->user->isGuest)
		{
			echo "please login first. We will redirect you to the login page in 3 secs";
			header("refresh:3;url=".Yii::app()->request->baseUrl);
		}
		else if(Yii::app()->user->userType=='s')
		{
			echo "you have no authority to view the buyer page";
		}
		else
		{
			$sitesArray = Sites::model()->with('tanks')->findAllByAttributes(array('organization_ID'=>Yii::app()->user->organizationID,'active'=>'1'));
			$res=array();
			foreach($sitesArray as $site)
			{
				$tankArray=array();
				foreach($site->tanks as $tank)
				{
					$tankArray[]=array('tank_ID'=>$tank->tank_ID, 'tank_name'=>$tank->tank_name, 'active'=>$tank->active);
				}
				$res["$site->site_ID"]=array($site->site_name, $tankArray);
			}
			$this->render('buyer', array("sitesArray"=>$res,"toolsArray" => Tools::model()->findAll()));
		}
	}
	
	/*
	 * retrieve tank monitor model by given mfg
	 */
	public function actionModels()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$res = TankMonitors::model()->getModelsByMFG($_POST['TankMonitors']['monitor_MFG']);
			echo CJSON::encode($res);
		}
	}
	
	/*
	 * called when submitting site detail changes
	 */
	public function actionDetails()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$siteAttributes=array();
			$siteAttributes['contact_name']=$_POST['Sites']['contact_name'];
			$siteAttributes['contact_cell_number']=$_POST['Sites']['contact_cell_number'];
			$siteAttributes['phone_number_of_site']=$_POST['Sites']['phone_number_of_site'];
			$siteAttributes['after_hour_number']=$_POST['Sites']['after_hour_number'];
			$siteAttributes['gated']=$_POST['Sites']['gated'];
			if($siteAttributes['gated']=='1')//is gated
			{
				$siteAttributes['gate_opens']=$_POST['Sites']['gate_opens'];
				$siteAttributes['gate_closes']=$_POST['Sites']['gate_closes'];
			}
			else
			{
				$siteAttributes['gate_opens']='00:00';
				$siteAttributes['gate_closes']='00:00';
			}
			$siteAttributes['security_on_premises']=$_POST['Sites']['security_on_premises'];
			if($siteAttributes['security_on_premises']=='1')
			{
				$siteAttributes['security_code']=$_POST['Sites']['security_code'];
			}
			else
			{
				$siteAttributes['security_code']='NULL';
			}
			$siteAttributes['open_time']=$_POST['Sites']['open_time'];
			$siteAttributes['close_time']=$_POST['Sites']['close_time'];
			$siteAttributes['directions']=$_POST['Sites']['directions'];
			$siteAttributes['notes']=$_POST['Sites']['notes'];
			$site=new Sites;
			$site->scenario='update-details';
			$site->attributes=$siteAttributes;
			if($site->validate())
			{
				$site->updateByPk($_POST['details_site_ID_field'], $siteAttributes);
				echo CJSON::encode('details-success');
			}
			else
				echo CJSON::encode($site->errors);
		}
	}
	
	/*
	 * called when submitting site profile changes
	 */
	public function actionProfile()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$siteAttributes=array();
			$siteAttributes['site_name']=$_POST['Sites']['site_name'];
			$siteAttributes['address1']=$_POST['Sites']['address1'];
			$siteAttributes['address2']=$_POST['Sites']['address2'];
			$siteAttributes['county']=$_POST['Sites']['county'];
			$siteAttributes['city']=$_POST['Sites']['city'];
			$siteAttributes['state']=$_POST['Sites']['state'];
			$siteAttributes['zip']=$_POST['Sites']['zip'];
			$siteAttributes['home_rack_ID']=$_POST['Sites']['home_rack_ID'];
			$site=new Sites;
			$site->scenario='update-profile';
			$site->attributes=$siteAttributes;
			if($site->validate())
			{
				$site->updateByPk($_POST['profile_site_ID_field'], $siteAttributes);
				foreach($_POST['tools'] as $tool_ID)
				{
					if($tool_ID>0)
					{
						SiteToolRelation::model()->replaceRecord($_POST['profile_site_ID_field'], $tool_ID);
					}
					else
					{
						SiteToolRelation::model()->deleteRecord($_POST['profile_site_ID_field'], $tool_ID*-1);
					}
				}			
				echo CJSON::encode('profile-success');
			}
			else
				echo CJSON::encode($site->errors);
		}
	}
	
	/*
	 * called when submitting tank changes
	 */
	public function actionTank()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$tank=new Tanks;
			$tank->scenario='update';
			$tankAttributes=array();
			$tankAttributes['tank_name']=$_POST['Tanks']['tank_name'];
			$tank->capacity=$_POST['Tanks']['capacity'];
			if($tank->validate(array('capacity')))
			{
				$fm = new CNumberFormatter(Yii::app()->getLocale());
				$tankAttributes['capacity']=$fm->format('#########.######',$_POST['Tanks']['capacity']*$_POST['unit_type']);
			}
			else
			{
				echo CJSON::encode($tank->errors);
				return;
			}
			$tankAttributes['tank_position_ID']=$_POST['Tanks']['tank_position_ID'];
			$tankAttributes['tank_type_ID']=$_POST['Tanks']['tank_type_ID'];
			$tankAttributes['pump_provided']=$_POST['Tanks']['pump_provided'];
		//	$tankAttributes['tank_drop_method_ID']=$_POST['Tanks']['tank_drop_method_ID'];
			$tankAttributes['product_ID']=$_POST['Tanks']['product_ID'];
			if(isset($_POST['Tanks']['tank_monitor_ID']))
				$tankAttributes['tank_monitor_ID']=$_POST['Tanks']['tank_monitor_ID'];
			else
				$tankAttributes['tank_monitor_ID']=NULL;
			$tankAttributes['remote_fill']=$_POST['Tanks']['remote_fill'];
			$tankAttributes['overfill_alarm']=$_POST['Tanks']['overfill_alarm'];

			$tank->attributes=$tankAttributes;
			if($tank->validate())
			{
				$tank->updateByPk($_POST['tank_ID_field'], $tankAttributes);
				echo CJSON::encode('tank-success');
			}
			else
				echo CJSON::encode($tank->errors);
		}
	}
	
	/*
	 * retrieve tank info by given tank ID
	 */
	public function actionTankInfo()
	{
		if(Yii::app()->request->isAjaxRequest)
		{			
			$tank_ID = $_POST['tankID'];
			$tank = Tanks::model()->with('site', 'product')->findByPk($tank_ID);
			$relationsArray = $tank->site->sitetoolRelation;
			$toolsArray = array();
			foreach($relationsArray as $relation)
			{
				$toolsArray[]=$relation->tool;
			}
			if($tank->tank_monitor_ID!=null)
				echo CJSON::encode(array($tank->site, $tank, $tank->tankMonitor, TankMonitors::model()->getModelsByMFG($tank->tankMonitor->monitor_MFG), $toolsArray, ProductTypes::model()->getProductsByCategory($tank->product->product_type_ID), $tank->product->product_type_ID));
			else
				echo CJSON::encode(array($tank->site, $tank, null, array()));
		}	
	}
	
	//problems with deleting because Auctions table uses tank_ID
	public function actionDeleteTank()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$tankID=$_POST['tank_ID'];
			
			$row=Tanks::model()->updateByPk($tankID, array('active'=>'0'));
			if($row==1)
				echo CJSON::encode('delete-tank-success');
			else
				echo CJSON::encode('delete-tank-fail');
		}
	}
	
	public function actionAddSite()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$sites=new Sites;
			
			if (!isset($_POST['site_name']) || $_POST['site_name'] == '')
				echo  CJSON::encode('add-site-error');	
			else if (!Sites::model()->siteExists($_POST['site_name']))
			{
				$sites->setIsNewRecord(true);
				$sites->site_name=$_POST['site_name'];
				$sites->organization_ID=Yii::app()->user->organizationID;
				$sites->address1=$_POST['address1'];
				$sites->address2=$_POST['address2'];
				$sites->county=$_POST['county'];
				$sites->city=$_POST['city'];
				$sites->state=$_POST['state'];
				$sites->zip=$_POST['zip'];
				$sites->home_rack_ID=$_POST['home_rack_ID'];
				$sites->active=1;
				$sites->save();
				echo  CJSON::encode('add-site-success');
			}
			else
				echo  CJSON::encode('add-site-fail');
		}
	}
	
	public function actionAddTank()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$orgproductRelation=new OrgProductRelation;
			$orgproductRelation->product_ID=$_POST['product_ID'];
			$orgproductRelation->organization_ID=Yii::app()->user->organizationID;
			if($orgproductRelation->save())
			{
				$productTypes = ProductTypes::model()->with('products', 'products.orgProRelation')->findAll(
								'organization_ID='.Yii::app()->user->organizationID
							);
				echo $this->renderPartial('productlist', array('productTypes'=>$productTypes), true);
			}
			else
				echo 'add-product-fail';
		}
	}
	
	/*
	 * retrieve site info by given site ID
	 */
	public function actionSiteInfo()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$site_ID = $_POST['ajax'];
			$site = Sites::model()->with('sitetoolRelation')->findByPk($site_ID);
			$relationsArray = $site->sitetoolRelation;
			$toolsArray = array();
			foreach($relationsArray as $relation)
			{
				$toolsArray[]=$relation->tool;
			}
			echo CJSON::encode(array($site, $toolsArray));
		}	
	}
}

?>
